package com.example.lotterysystem.common.utils;

import com.example.lotterysystem.common.pojo.CommonResult;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;
import org.springframework.util.ReflectionUtils;

import java.util.List;
import java.util.concurrent.Callable;

/**
 * Created with IntelliJ IDEA.
 * Description: 数据的序列化与反序列化
 * User: Spider-Man
 * Date: 2025-09-03
 * Time: 17:46
 */
public class JacksonUtil {

    private JacksonUtil() {

    }
    /**
     * 采用单例模式
     */
    private final static ObjectMapper OBJECT_MAPPER;


    static {
        //单例模式的实现, 饿汉模式, 先创建对象, 使用时直接调用
        OBJECT_MAPPER = new ObjectMapper();
    }

    private static ObjectMapper getObjectMapper() {
         return OBJECT_MAPPER;
    }

    //实际调用的方法.
    private static <T> T tryParse(Callable<T> parser) {
        return tryParse(parser, JacksonException.class);
    }

    private static <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return parser.call();
        } catch (Exception var4) {
            if (check.isAssignableFrom(var4.getClass())) {
                throw new JsonParseException(var4);
            }
                throw new IllegalStateException(var4);
        }
    }

    /**
     * 序列化方法
     * @param object
     * @return
     */
    //提供给外部调用的序列化方法.
    public static String writeValueAsString(Object object) {
        return JacksonUtil.tryParse(() -> {
            return JacksonUtil.getObjectMapper().writeValueAsString(object);
        });
    }

    /**
     * 反序列化Object方法
     * @param content
     * @param valueType
     * @return
     * @param <T> 占位, 知道具体的类型
     */
    public static <T> T readValue(String content, Class<T> valueType) {
        return JacksonUtil.tryParse(() -> {
           return JacksonUtil.getObjectMapper().readValue(content,valueType);
        });
    }

    //List反序列化方法
    //<?> 未知类型
    public static <T> T readListValue(String content, Class<?> paramClasses) {
        JavaType javaType = JacksonUtil.getObjectMapper().getTypeFactory()
                .constructParametricType(List.class, CommonResult.class);
        return JacksonUtil.tryParse(() -> {
            return JacksonUtil.getObjectMapper().readValue(content,javaType);
        });
    }
}
